<template>
  <div class="file-upload-wrapper">
    <!-- 图片上传 -->
    <div v-if="fileType === 'image'" class="image-upload">
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :disabled="disabled"
        class="image-uploader"
      >
        <div v-if="modelValue" class="image-preview">
          <img :src="getImageUrl(modelValue as string)" :alt="alt" />
          <div class="image-overlay">
            <el-icon class="overlay-icon" @click.stop="previewImage">
              <ZoomIn />
            </el-icon>
            <el-icon class="overlay-icon" @click.stop="removeImage">
              <Delete />
            </el-icon>
          </div>
        </div>
        <div v-else class="upload-placeholder">
          <el-icon class="upload-icon">
            <Plus />
          </el-icon>
          <div class="upload-text">{{ placeholder || '点击上传图片' }}</div>
          <div class="upload-tip" v-if="tip">{{ tip }}</div>
        </div>
      </el-upload>
    </div>

    <!-- 文件上传 -->
    <div v-else class="file-upload">
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="uploadHeaders"
        :show-file-list="true"
        :file-list="fileList"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :on-remove="handleRemove"
        :disabled="disabled"
        :multiple="multiple"
        :limit="limit"
        :on-exceed="handleExceed"
      >
        <el-button type="primary" :disabled="disabled">
          <el-icon><Upload /></el-icon>
          {{ buttonText || '选择文件' }}
        </el-button>
        <template #tip>
          <div class="el-upload__tip" v-if="tip">
            {{ tip }}
          </div>
        </template>
      </el-upload>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="60%" center>
      <img :src="getImageUrl(modelValue as string)" style="width: 100%; height: auto;" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, ZoomIn, Delete } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'

// 组件名称
defineOptions({
  name: 'FileUpload'
})

// Props
interface Props {
  modelValue?: string | string[]
  fileType?: 'image' | 'file'
  accept?: string
  maxSize?: number // MB
  placeholder?: string
  tip?: string
  buttonText?: string
  alt?: string
  disabled?: boolean
  multiple?: boolean
  limit?: number
  siteId?: number // 站点ID
}

const props = withDefaults(defineProps<Props>(), {
  fileType: 'image',
  accept: 'image/*',
  maxSize: 20, // 增加到20MB
  disabled: false,
  multiple: false,
  limit: 1
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string | string[]]
  'change': [value: string | string[]]
}>()

// 响应式数据
const uploadRef = ref()
const previewVisible = ref(false)

// 上传配置
const uploadUrl = computed(() => {
  if (props.siteId) {
    return `/cms/admin/attachment/upload/${props.siteId}`
  }
  return '/cms/admin/attachment/upload'
})

const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${getToken()}`
}))

// 文件列表（用于文件上传模式）
const fileList = computed(() => {
  if (props.fileType === 'file' && props.modelValue) {
    if (Array.isArray(props.modelValue)) {
      return props.modelValue.map((url, index) => ({
        name: `文件${index + 1}`,
        url: url,
        uid: index
      }))
    } else {
      return [{
        name: '文件',
        url: props.modelValue,
        uid: 0
      }]
    }
  }
  return []
})

// 获取完整图片URL
const getImageUrl = (url: string) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `/cms${url}`
}

// 上传前验证
const beforeUpload = (file: File) => {
  // 文件类型验证
  if (props.accept && !file.type.match(props.accept.replace(/\*/g, '.*'))) {
    ElMessage.error(`请选择正确的文件类型`)
    return false
  }

  // 文件大小验证
  const isLtMaxSize = file.size / 1024 / 1024 < props.maxSize
  if (!isLtMaxSize) {
    ElMessage.error(`文件大小不能超过 ${props.maxSize}MB`)
    return false
  }

  return true
}

// 上传成功
const handleSuccess = (response: any) => {
  if (response.code === 0) {
    const fileUrl = response.data.url
    
    if (props.multiple && Array.isArray(props.modelValue)) {
      const newValue = [...props.modelValue, fileUrl]
      emit('update:modelValue', newValue)
      emit('change', newValue)
    } else {
      emit('update:modelValue', fileUrl)
      emit('change', fileUrl)
    }
    
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 上传失败
const handleError = (error: any) => {
  console.error('Upload error:', error)
  ElMessage.error('上传失败，请重试')
}

// 移除文件
const handleRemove = (file: any) => {
  if (props.multiple && Array.isArray(props.modelValue)) {
    const newValue = props.modelValue.filter((url, index) => index !== file.uid)
    emit('update:modelValue', newValue)
    emit('change', newValue)
  } else {
    emit('update:modelValue', '')
    emit('change', '')
  }
}

// 移除图片
const removeImage = () => {
  ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    emit('update:modelValue', '')
    emit('change', '')
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 预览图片
const previewImage = () => {
  previewVisible.value = true
}

// 文件数量超出限制
const handleExceed = () => {
  ElMessage.warning(`最多只能上传 ${props.limit} 个文件`)
}
</script>

<style scoped lang="scss">
.file-upload-wrapper {
  .image-upload {
    .image-uploader {
      :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;

        &:hover {
          border-color: #409eff;
        }
      }

      .image-preview {
        position: relative;
        width: 148px;
        height: 148px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 6px;
        }

        .image-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 16px;
          opacity: 0;
          transition: opacity 0.3s;
          border-radius: 6px;

          &:hover {
            opacity: 1;
          }

          .overlay-icon {
            color: white;
            font-size: 20px;
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            transition: background-color 0.3s;

            &:hover {
              background: rgba(255, 255, 255, 0.2);
            }
          }
        }
      }

      .upload-placeholder {
        width: 148px;
        height: 148px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #8c939d;

        .upload-icon {
          font-size: 28px;
          margin-bottom: 8px;
        }

        .upload-text {
          font-size: 14px;
          margin-bottom: 4px;
        }

        .upload-tip {
          font-size: 12px;
          color: #c0c4cc;
        }
      }
    }
  }

  .file-upload {
    :deep(.el-upload-list) {
      margin-top: 8px;
    }
  }
}
</style>
